package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mrchen
 * @date 2022/1/6 10:41
 */
@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {

    @Autowired
    Configuration configuration;


    @Autowired
    @Qualifier("minIOFileStorageService")
    FileStorageService fileStorageService;

    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    AuthorMapper authorMapper;

    @Value("${file.minio.prefix}")
    String prefix;

    /**
     * @param content  文章内容
     * @param apArticle   文章对象
     */
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        try {
            // 1.  获取模板对象
            Template template = configuration.getTemplate("article.ftl");
            // 2.  准备替换模板的数据
            Map param = new HashMap<>();
            param.put("article",apArticle);
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            if (apAuthor == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章作者信息不存在");
            }
            param.put("authorApUserId",apAuthor.getUserId());
            param.put("content", JSON.parseArray(content,Map.class));
            // 3.  替换模板 并输出到 指定地方
            StringWriter stringWriter = new StringWriter();
            template.process(param,stringWriter);
            // 将字符内容转化为输入流
            InputStream in = new ByteArrayInputStream(stringWriter.toString().getBytes());
            // 4.  上传到 minIO中 得到的路径 修改apArticle ==> static_url字段
            String storePath = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", in);
            apArticle.setStaticUrl(storePath);
            apArticleMapper.updateById(apArticle);
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"页面静态化失败，原因: 未找到模板"+e.getMessage());
        } catch (TemplateException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"页面静态化失败，原因: 替换模板失败"+e.getMessage());
        }
    }
}